package com.music.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class FileLoadController {
    @RequestMapping("/fileUpload")
    public String testResponseJson(String picname,
                                   MultipartFile uploadFile,
                                   HttpServletRequest request) throws Exception {
        // ⼀.定义⽂件名
        String fileName = "";
        // 1.获取原始⽂件名
        String uploadFileName = uploadFile.getOriginalFilename();
        // 2.截取⽂件扩展名
        String extendName = uploadFileName.substring(uploadFileName.lastIndexOf(".") +
                1);
        // 3.把⽂件加上随机数，防⽌⽂件重复
        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        // 4.判断是否输⼊了⽂件名
        if (!StringUtils.isEmpty(picname)) {
            fileName = uuid + "_" + picname + "." + extendName;
        } else {fileName = uuid + "_" + uploadFileName;
        }
        System.out.println(fileName);
        // ⼆.获取⽂件路径
        ServletContext context = request.getSession().getServletContext();
        String basePath = context.getRealPath("/uploads");
        // 三.解决同⼀⽂件夹中⽂件过多问题
        String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        // 四.判断路径是否存在
        File file = new File(basePath + "/" + datePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        // 5.使⽤ MulitpartFile 接⼝中⽅法，把上传的⽂件写到指定位置
        uploadFile.transferTo(new File(file, fileName));
        return "success";
    }
}
